<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2019/6/20
 * Time: 11:12
 */

namespace app\admin\controller;


use think\Db;
use think\Request;

class Aftersaleyet extends Base
{
    /**
     * 支付宝
     * @var array
     */
    protected $config = array(
        'partner' => '2088621781822784',//用不着
        'seller_id' => 'admin@bagepanzi.com',//用不着
        'sign_type' => 'RSA2',// 直接写死了
        'it_b_pay' => '10m',//用不着
        'md5' => 'djqm7budkdlki6a76yasuyb9s1riiu1j',//用不着
        'ali_public' => 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsF8OKGkWhR7IcTZjJZg/rEPiq7Ehc/4jhtoyKx62YvBZr/OJ4of6Mrn/1RSOayYRj7WIAnDg87TRbTxj7xWtRXFoHpSRemUobtYFPFIUug2BImaPDvDae+/ZXJhzcmdV2ChUA/1DOchYcry/MblFZIYDVxXU+tZL+Din8c9bGPWI4uoKB7rXd3c5oSHFmAX5K4l33xGF/PtUWpK/DpzABE46DQt7ZcuRYN53C/CRWRG+7NG73vFqjgwsSnaZjQXw/c4cSSAZ4oUkVMi9nU4nIkhp140R2aW86uRKNgHUNt4sFy6NOOegRV6m5sjqtZpkAZtCkN9inwlXtda0Dm6UjwIDAQAB',
        'public_key' => "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA1xh8a1HUp8IYM9Bu0OXDGo6/2dRYgIic5MDU5qvDTbyiM+p8gl8dVgp2PqMeADExJK6UwayEXFypnr1hQcd613Npg+VKyiaLqVmY0WUDxjlRMj2qEXgx0ZBzKdM33g1218yG5QA/b9LO3/K+FByrFFLtL4gpAdhpcRcKYTYCMaUC5nKug0uguschFD7dY2pnOeL11t6wIup37/NCuwx+h3sjhPnWXr/Q/TltGMBUhFaSfnCxl3ejK803UuloQhiJRoCeBguYqfHT+EZLOTtDXa6DmpZwp3IjP8Fg70isVYXV2QIeqDKsLQpi3huVQA0ordotddUsiFBEMzslQ41BXQIDAQAB",
        'private_key' => 'M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yMKifwriB/czs5W7alVibQgraTpRwOmNI7mMqjywrYSr1uxqrKWO2CciMz4CpuOTUopQLltv5zcOgD+WceQXNxLqAZef9YAX7hovj5bEHZ4H+uH3aFTND4FMetApkYFCEQUNOL+6uBirwY0EvGq/QWXr5ECgYEAhZiqC6y1T6NBt7X+R+dm51VutmZx4TC0GQp3gLd85+YD+LVlkjNyHf3XzCAaCbLyGlU4al9D5moXxbGKFTFkOhDiE8/QRtjuCHy/WMTcbnNuHq/TbAB3p2S3u7EFsHmKEX6ZhsRl/PVN1yARyZDqEmMaEjzGHgZWBAQqXuMtNeECgYAcXL6LPsIQp/B3UagHqpyi0iR/RO5QMIt1wJy1Z5Ltyz2AfKBa3Y9J0xETJMwFq2RJ7CsLwazm9BIZDIVpiGp6lkNdtu9YYy108y3VkIo/EHZDQqpC0DwgB+0NxAyYWy9U2Zl383twdLssoWZxtqh0HKeH9MvqqlDeuiq5+L+4gA=='
    );
    
    /**
     * 微信
     * @var array
     */
    private $config1 = array(
        'APPID' => 'wx0ae8c912db07c4dd', // 微信支付APPID.
        'MCHID' => '1502805281', // 微信支付MCHID 商户收款账号
        'KEY' => 'JD4sGRAmJSzlPYKdohaL561nGBOQW3ba', // 微信支付KEY
//        'APPSECRET' => '6a54b5e88c2dd87159bfeca466a9a770', // 公众帐号secert (公众号支付专用)
//        'NOTIFY_URL' => 'http://heart.xuanwumobile.com/api/Weixin/huidiao', // 接收支付状态的连接
    );
    
    /**
     * 已审核售后列表
     * @return mixed|\think\response\Json
     */
    public function index()
    {
        if(request()->isAjax()) {
            $update_start = input('update_start');
            $update_end = input('update_end');
            $oi_good_name = input('keyword');
            $oi_after_status = input('oi_after_status');
            $after_user_num = input('after_user_num');
            $after_status = input('after_status');
            $oi_is_rerturn = input('oi_is_rerturn');
            $where = [];
            $where['oi_after_status'] = ['neq', 1];
            $where['after_status'] = ['IN', '2,3,4,5,6'];
            //申请日期
            if(isset($update_start) && $update_start != '' && isset($update_end) && $update_end != '') {
                $where['after_time'] = ['between', [$update_start, $update_end]];
            }
            if(isset($update_start) && $update_start != '' && isset($update_end) && $update_end == '') {
                $where['after_time'] = ['>=', $update_start];
            }
            if(isset($update_start) && $update_start == '' && isset($update_end) && $update_end != '') {
                $where['after_time'] = ['<=', $update_end];
            }
            //商品名称
            if(isset($oi_good_name) && $oi_good_name != '') {
                $where['oi_good_name'] = ['like', '%' . $oi_good_name . '%'];
            }
            //用户物流单号
            if(isset($after_user_num) && $after_user_num != '') {
                $where['after_user_num'] = ['like', '%' . $after_user_num . '%'];
            }
            //售后类型
            if(isset($oi_after_status) && $oi_after_status != '') {
                $where['oi_after_status'] = $oi_after_status;
            }
            //审核结果
            if(isset($after_status) && $after_status != '') {
                if($after_status == 3) {
                    $where['after_status'] = $after_status;
                } else {
                    $where['after_status'] = ['IN', '2,4,5,6'];
                }
            }
            //是否需要回寄
            if(isset($oi_is_rerturn) && $oi_is_rerturn != '') {
                $where['oi_is_rerturn'] = $oi_is_rerturn;
            }
            $Nowpage = input('page') ? input('page') : 1;
            $limits = input("limit") ? input("limit") : 10;
            // 获取总条数
            $count = Db::name('order_info')
                ->join('up_exchange ue', 'ue.exchange_id = after_exchange_id', 'left')
                ->join('up_return ur', 'ur.exchange_id = after_return_id', 'left')
                ->join('up_u_user', 'oi_user_id = user_id', 'left')
                ->join('up_order', 'oi_order_id = order_id', 'left')
                ->where($where)
                ->count();
            $lists = Db::name('order_info')
                ->join('up_exchange ue', 'ue.exchange_id = after_exchange_id', 'left')
                ->join('up_return ur', 'ur.exchange_id = after_return_id', 'left')
                ->join('up_u_user', 'oi_user_id = user_id', 'left')
                ->join('up_order', 'oi_order_id = order_id', 'left')
                ->field('oi_good_name, oi_price, oi_type, oi_num, oi_after_status, ur.exchange_name as return_name,
                ue.exchange_name, after_reason, after_num, after_time, user_username, after_spec_id, oi_id, 
                after_user_courier, after_user_num, after_us_courier, after_us_num, after_status, 
                oi_is_rerturn, oi_good_id, oi_spec_id, after_order_num, order_name, order_address, 
                order_phone, order_freight_money, order_user_pay')
                ->where($where)
                ->page($Nowpage, $limits)
                ->order('after_time desc')
                ->select();
            foreach($lists as $key => $vo) {
                if($vo['oi_type'] == 1) { //非图书
//                    if($vo['after_spec_id'] == ''){ //没有规格
//                        $spec = Db::table('up_good_spec')
//                            ->where('spec_id', $vo['oi_spec_id'])
//                            ->field('spec_name, spec_stock')
//                            ->find();
//                    }else{
                    $spec = Db::table('up_good_spec')
                        ->where('spec_id', $vo['after_spec_id'])
                        ->field('spec_name, spec_stock')
                        ->find();
//                    }
                    $lists[$key]['ISBN'] = '';
                    $lists[$key]['spec_stock'] = $spec['spec_stock'];
                    $lists[$key]['spec_name'] = $spec['spec_name'];
                } else {
                    $goodInfo = Db::table('up_goods')
                        ->field('good_isbn, good_stock')
                        ->where('good_id', $vo['oi_good_id'])
                        ->find();
                    $lists[$key]['ISBN'] = $goodInfo['good_isbn'];
                    $lists[$key]['spec_stock'] = $goodInfo['good_stock'];
                    $lists[$key]['spec_name'] = '';
                }
            }
            return json(['code' => 220, 'msg' => '', 'count' => $count, 'data' => $lists]);
        }
        return $this->fetch('aftersaleyet/index');
    }
    
    /**
     * 发货
     * @return \think\response\Json
     */
    public function confirmSend()
    {
        if(Request::instance()->isPost()){
            $oi_id = input('oi_id');
            $after_us_courier = trim(input('after_us_courier'), ' ');
            $after_us_num = trim(input('after_us_num'), ' ');
            $update = [
                'after_status' => 6,
                'after_us_courier' => $after_us_courier,
                'after_us_num' => $after_us_num
            ];
            Db::startTrans();
            try{
                //时间轴
                Db::table('up_after_sale_time')
                ->insert([
                    'ast_after_oi_id' => $oi_id,
                    'ast_after_time' => date('Y-m-d H:i:s'),
                    'ast_after_content' => '平台已收到您的换货商品，更换的商品已按您的收货地址寄出，请注意查收！',
                ]);
                //订单详情状态
                Db::table('up_order_info')->where('oi_id', $oi_id)->update($update);
                Db::commit();
                $res = 1;
            }catch(\Exception $e){
                Db::rollback();
                $res = 2;
            }
            if($res == 1) {
                return json(['code' => 200, 'msg' => '发货成功']);
            } else {
                return json(['code' => 100, 'msg' => '发货失败']);
            }
        }
        $id = input('oi_id');
        $this->assign('oi_id', $id);
        return $this->fetch('aftersaleyet/confirmsend');
        
    }
    
    /**
     * 退款
     * @return mixed|\think\response\Json
     */
    public function returnMoney()
    {
        if(Request::instance()->isPost()) {
            $id = input('oi_id');
            $after_price = input('after_price');
            $order_info = Db::table('up_order_info')
                ->field('oi_order_id, oi_price, after_num,after_status')
                ->where('oi_id', $id)
                ->find();
            $user_pay = Db::table('up_order')->where('order_id', $order_info['oi_order_id'])->value('order_user_pay');
            if($order_info['after_status'] == 5){
                return json(['code' => 100, 'msg' => '此商品已经退款过了']);
            }
            //判断退款金额是否大于成交金额
            if($after_price > $user_pay) {
                return json(['code' => 100, 'msg' => '退款金额不可超过成交金额']);
            }
            $insert = [
                'ast_after_content' => '平台已退款，退款将于1-3个工作日内按原支付路径返还',
                'ast_after_oi_id' => $id,
                'ast_after_time' => date('Y-m-d H:i:s')
            ];
            $update = [
                'after_status' => 5,
                'after_price' => $after_price
            ];
            $order = Db::table('up_order')
                ->field('order_type, order_number')
                ->where('order_id', $order_info['oi_order_id'])
                ->find();
            //退款
            if($order['order_type'] == 1) { //支付宝
                $sucessss = $this->aliReturn($after_price, $order['order_number'], $id, $update, $insert);
            } else { //微信
                $sucessss = $this->weixiReturn($user_pay, $after_price, $order['order_number'], $order_info['after_num']);
            }
            if($sucessss['status'] == 200){
                Db::startTrans();
                try {
                    //更新订单详情表
                    Db::table('up_order_info')->where('oi_id', $id)->update($update);

                    //插入时间轴表
                    Db::table('up_after_sale_time')->insert($insert);

                    Db::commit();
                    return json(['code' => 200, 'msg' => '退款成功']);
                } catch(\Exception $e) {
                    Db::rollback();
                    return json(['code' => 100, 'msg' => '退款失败']);
                }
            }else{
                return json(['code' => 100, 'msg' => $sucessss['msg']]);
            }

        }
        $oi_id = input('oi_id');
        $this->assign('oi_id', $oi_id);
        return $this->fetch('aftersaleyet/returnmoney');
    }
    
    //**************************************** 支付宝
    /**
     * 阿里退款
     * @param $money   退款金额
     * @param $num     订单号
     */
    public function aliReturn($money, $num)
    {
        $payInfo = array();
        $payInfo['number'] = $num;
        $payInfo['money'] = $money;
        //仨参数：money,number
        import('alipay.aop.AopClient', EXTEND_PATH);
        import('alipay.aop.request.AlipayTradeRefundRequest', EXTEND_PATH);
        $aop = new \AopClient;
        $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
        $aop->appId = '2019033063737847';
        $aop->rsaPrivateKey = $this->config['private_key'];
        $aop->alipayrsaPublicKey = $this->config['ali_public']; //不应该用这个，用ali_public
        $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset = 'UTF-8';
        $aop->format = 'json';
        $request = new \AlipayTradeRefundRequest;
        $refundAmount = $payInfo['money'];
        $request->setBizContent("{" .
            "\"out_trade_no\":\"" . $payInfo['number'] . "\"," .
            "\"trade_no\":\"\"," .
            "\"refund_amount\":" . $refundAmount . "," .
            "\"refund_reason\":\"退款\"" .
            "  }");
        $result = $aop->execute($request);
        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        $resultCode = $result->$responseNode->code;
        if(!empty($resultCode) && $resultCode == 10000) {
            return array('status' => 200, 'msg' => '操作成功');
        } else {
            return array('status' => 0, 'msg' => '调用接口失败');
        }
    }
    
    //************************************* 微信
    /**
     * 微信退款
     * @param $total_fee       订单金额
     * @param $refund_fee      退款金额
     * @param $out_trade_no    付款时的订单号
     * @param $out_refund_no   退款订单号
     * @return array
     */
    public function weixiReturn($total_fee, $refund_fee, $out_trade_no, $out_refund_no){
        $url = 'https://api.mch.weixin.qq.com/secapi/pay/refund'; //请求地址
        //请求数据
        $config_data = [
            'appid' => $this->config1['APPID'],
            'mch_id' => $this->config1['MCHID'],
            'nonce_str' => $this->getRandChar(32),
            'out_trade_no' => $out_trade_no, //支付订单号
            'out_refund_no' => $out_refund_no, //退款单号
            'total_fee' => $total_fee * 100, //订单金额
            'refund_fee' => $refund_fee * 100, //退款金额
        ];
        $config_data['sign'] = $this->makeSign($config_data);
        $data = $this->toXml($config_data);
        $responseArr = $this->toArray($this->httpRequest($url, $data));
//        return $res;
        if(!is_array($responseArr) || count($responseArr)<=0){
            $return['msg'] = '网络请求繁忙';
            $return['status'] = 0;
        }else if($responseArr['return_code'] == 'FAIL'){
            $return['msg'] = $responseArr['return_msg'];
            $return['status'] = 0;
        }else{
            //二次签名
            $return['text'] = $responseArr;
//			直接返回
            $return['status'] = 200;
        }
        return $return;
        
    }
    
    /*
     * 发送请求
     * @param  string $url      请求的url地址
     * @param  array  $postData 请求的数据
     */
    public function httpRequest($url, $postData = [])
    {
        $header[] = "Content-type: text/xml";//定义content-type为xml,注意是数组
        // 初始化curl
        $ch = curl_init();
        // 设置请求的url地址
        curl_setopt($ch, CURLOPT_URL, $url);
        // 将curl_exec()获取的信息以字符串返回，而不是直接输出。
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        // 发送post请求
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        //curl注意事项，如果发送的请求是https，必须要禁止服务器端校检SSL证书
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch,CURLOPT_SSLCERTTYPE,'pem');
        curl_setopt($ch,CURLOPT_SSLCERT,ROOT_PATH.'/public/apiclient_cert.pem');
        curl_setopt($ch,CURLOPT_SSLCERTTYPE,'pem');
        curl_setopt($ch,CURLOPT_SSLKEY,ROOT_PATH.'/public/apiclient_key.pem');
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        
        // 执行curl
        $result = curl_exec($ch);
        if(curl_errno($ch)){
            print curl_error($ch);
        }
        // 关闭curl
        curl_close($ch);
        
        return $result;
    }
    
    /**
     * 生成签名
     * @return 签名，本函数不覆盖sign成员变量，如要设置签名需要调用SetSign方法赋值
     */
    public function makeSign($data){
        // 去空
        $data=array_filter($data);
        //签名步骤一：按字典序排序参数
        ksort($data);
        $string_a=http_build_query($data);
        $string_a=urldecode($string_a);
        //签名步骤二：在string后加入KEY
        $config1=$this->config1;
        $string_sign_temp=$string_a."&key=".$config1['KEY'];
        //签名步骤三：MD5加密
        $sign = md5($string_sign_temp);
        // 签名步骤四：所有字符转为大写
        $result=strtoupper($sign);
        return $result;
    }
    
    /**
     * 输出xml字符
     * @throws WxPayException
     **/
    public function toXml($data){
        //var_dump($data);
        if(!is_array($data) || count($data) <= 0){
            //throw new WxPayException("数组数据异常！");
        }
        $xml = "<xml>";
        foreach ($data as $key=>$val){
            if (is_numeric($val)){
                $xml.="<".$key.">".$val."</".$key.">";
            }else{
                $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
            }
        }
        $xml.="</xml>";
        return $xml;
    }
    
    /**
     * 将xml转为array
     * @param  string $xml xml字符串
     * @return array       转换得到的数组
     */
    public function toArray($xml){
        //禁止引用外部xml实体
        libxml_disable_entity_loader(true);
        $result= json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $result;
    }
    
    /**
     * 获取指定长度的随机字符串
     * @param $length
     * @return null|string
     */
    function getRandChar($length){
        $str = null;
        $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
        $max = strlen($strPol)-1;
        for($i=0;$i<$length;$i++){
            $str.=$strPol[rand(0,$max)];//rand($min,$max)生成介于min和max两个数之间的一个随机整数
        }
        return $str;
    }
}